import { useEffect, useRef } from 'react'
import THREEProject from '../utils/index'
import {arrNomarlize} from '../utils/helper'

const BufferGeometryII = () => {
  const can = useRef(null)
  const pro = new THREEProject([1, 1, 1])
  const { thr, renderer, scene, axes, camera, controls } = pro
  const fileLoader = new thr.FileLoader()
  const init = () => {
    scene.add(axes)

    const geometry = new thr.BufferGeometry()
   
    const material = new thr.MeshBasicMaterial({
      side: thr.DoubleSide,
      vertexColors: thr.VertexColors
    })
    fileLoader.load('/assets/GBDplot_trisurf_xzy二维数组.json', res => {
      console.log('dataJSON', JSON.parse(res).data)
      const {vertices, colors} = arrNomarlize(JSON.parse(res).data)
      console.log('list', colors)
      geometry.setAttribute('position', new thr.BufferAttribute(new Float32Array(vertices.reverse()), 3))
      geometry.setAttribute('color', new thr.BufferAttribute(new Float32Array(colors), 3))
      console.log("🚀 ~ file: BufferGeometryII.js ~ line 14 ~ init ~ geometry", geometry)
      const mesh = new thr.Mesh(geometry, material)
      scene.add(mesh)
    })
    scene.add(new thr.AmbientLight(0xffffff))
    appendRenderDom()
    animate()
  }


  const appendRenderDom = () => {
    if(!can.current.children.length) {
      can.current.appendChild(renderer.domElement)
    }
  }

  const render = () => {
    controls.update()
    renderer.render(scene, camera)
  }

  const animate = () => {
    requestAnimationFrame(animate)
    render()
  }

  useEffect(init, [])

  return (
    <div ref={can}></div>
  )
}

export default BufferGeometryII
export {
  BufferGeometryII
}